<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of StreamController
 *
 * @author QuangKhoi
 */
class StreamController {

    /**
     * Store model object
     * @var Stream
     */
    private $model;

    /**
     * Store view for the stream
     * @var StreamView
     */
    private $view;

    /**
     * 
     * @param type $model
     * @param type $view
     */
    public function __construct($model, $view) {
        $this->model = $model;
        $this->view = $view;
    }

    /**
     * 
     * @param DateTime $startDate
     * @param DateTime $endDate
     * @return Int
     */
    public function count($startDate, $endDate) {
        $query = trim($this->model->query);
        $language = $this->model->language;
        $timezone = 7;

        //Language: 2 = vi, 0 = all
        $zMessage = new ZMessageReader($startDate, $endDate, $timezone, $query, $language, 0, 0);
        $collection = $zMessage->read();
        return $collection->getTotal();
    }

    public static function getSMTIcon($type) {
        switch ($type) {
            case 0:
                return "boards";
            case 1:
                return "boards";
            case 2:
                return "news";
            case 3:
                return "blogs";
            case 4:
                return "facebook";
            case 5:
                return "twitter";
            case 6:
                return "youtube";
            case 7:
                return "classifieds";
            case 8:
                return "googleplus";
            case 9:
                return "retailers";
        }
    }

    /**
     * 
     * @param Int $streamId
     */
    public function render($startDate, $endDate, $index, $length, $language = 0, $tag =  array('0'), $sentiment = 0, $messageAction = '', $type =  array('0'), $source = array('0')) {
        //Need to edit
        $source = implode('" | "', $source);
        $source = urldecode($source);
        $query = trim($this->model->query);
        $timezone = 7;
        //Param parser
        #remove the directory path we don't want 
        $url = $_SERVER['REQUEST_URI'];
        $request = ltrim($url, '/');
        if (strpos($request, '?') != '') {
            $request = substr($request, 0, strpos($request, "?"));
        }
        #split the path by '/'
        $params = split("/", $request);
        $error = '';
        $signals = array();
        //Get last access
        $lastAccess = $this->model->getStreamInfo();
        $totalSpamMessages = 0;
        $totalMessages = 0;
        $newMessages = 0;
        $newSpamMessages = 0;
        $totalSpamLeads = 0;
        $newSpamLeads = 0;
        $totalLeads = 0;
        $newLeads = 0;
        if (strtoupper($params[0]) == 'INFO') {
            /*
              $dStartDate = new DateTime($startDate);
              if ($lastAccess < $dStartDate) {
              $lastAccess = $dStartDate;
              }
              $normalQuery = SpamMessages::getQuery($this->model->streamId);
              $spamQuery = SpamMessages::getSQuery($this->model->streamId);

              //Query total of messages
              if ($type) {
              $zMessage = new ZPulseReader($startDate, $endDate, $timezone, $query . $normalQuery, $language, (array) $type);
              } else {
              $zMessage = new ZPulseReader($startDate, $endDate, $timezone, $query . $normalQuery, $language);
              }
              try {
              $zMessage->read(function($item, $replies, $total) use (&$items, &$totalMessages) {
              $totalMessages = $total;
              }, $index, 0);
              } catch (Exception $err) {
              $totalMessages = 0;
              }
              //Query total of new Messages
              $curDate = new DateTime();
              if ($type) {
              $zMessage = new ZPulseReader($lastAccess->format("d-m-Y H:i:s"), $curDate->format("d-m-Y H:i:s"), $timezone, $query . $normalQuery, $language, (array) $type);
              } else {
              $zMessage = new ZPulseReader($lastAccess->format("d-m-Y H:i:s"), $curDate->format("d-m-Y H:i:s"), $timezone, $query . $normalQuery, $language);
              }
              try {
              $zMessage->read(function($item, $replies, $total) use (&$items, &$newMessages) {
              $newMessages = $total;
              }, $index, 0);
              } catch (Exception $err) {
              $newMessages = 0;
              }

              //Query total of spam messages
              if ($type) {
              $zMessage = new ZPulseReader($startDate, $endDate, $timezone, $query . $spamQuery, $language, (array) $type);
              } else {
              $zMessage = new ZPulseReader($startDate, $endDate, $timezone, $query . $spamQuery, $language);
              }
              try {
              $zMessage->read(function($item, $replies, $total) use (&$items, &$totalSpamMessages) {
              $totalSpamMessages = $total;
              }, $index, 0);
              } catch (Exception $err) {
              $totalSpamMessages = 0;
              }

              //Query total of new Spam Messages
              $curDate = new DateTime();
              if ($type) {
              $zMessage = new ZPulseReader($lastAccess->format("d-m-Y H:i:s"), $curDate->format("d-m-Y H:i:s"), $timezone, $query . $spamQuery, $language, (array) $type);
              } else {
              $zMessage = new ZPulseReader($lastAccess->format("d-m-Y H:i:s"), $curDate->format("d-m-Y H:i:s"), $timezone, $query . $spamQuery, $language);
              }
              try {
              $zMessage->read(function($item, $replies, $total) use (&$items, &$newSpamMessages) {
              $newSpamMessages = $total;
              }, $index, 0);
              } catch (Exception $err) {
              $newSpamMessages = 0;
              }

              //Total Spam Leads
              if ($type) {
              $zLeadMessage = new ZLeadReader($startDate, $endDate, $timezone, $query . $spamQuery, $language, (array) $type);
              } else {
              $zLeadMessage = new ZLeadReader($startDate, $endDate, $timezone, $query . $spamQuery, $language);
              }
              try {
              $zLeadMessage->read(function($item, $total) use (&$totalSpamLeads) {
              $totalSpamLeads = $total;
              }, $index, 0);
              } catch (Exception $err) {
              $totalSpamLeads = 0;
              }

              //Total new Spam Leads
              $curDate = new DateTime();
              if ($type) { // have smt filter
              $zLeadMessage = new ZLeadReader($lastAccess->format("d-m-Y H:i:s"), $curDate->format("d-m-Y H:i:s"), $timezone, $query . $spamQuery, $language, (array) $type);
              } else {
              $zLeadMessage = new ZLeadReader($lastAccess->format("d-m-Y H:i:s"), $curDate->format("d-m-Y H:i:s"), $timezone, $query . $spamQuery, $language);
              }
              try {
              $zLeadMessage->read(function($item, $total) use (&$newSpamLeads) {
              $newSpamLeads = $total;
              }, $index, 0);
              } catch (Exception $err) {
              $newSpamLeads = 0;
              }

              //Total Leads
              if ($type) {
              $zLeadMessage = new ZLeadReader($startDate, $endDate, $timezone, $query, $language, (array) $type);
              } else {
              $zLeadMessage = new ZLeadReader($startDate, $endDate, $timezone, $query, $language);
              }
              try {
              $zLeadMessage->read(function($item, $total) use (&$totalLeads) {
              $totalLeads = $total;
              }, $index, 0);
              } catch (Exception $err) {
              $totalLeads = 0;
              }

              //Total new Leads
              $curDate = new DateTime();
              if ($type) { // have smt filter
              $zLeadMessage = new ZLeadReader($lastAccess->format("d-m-Y H:i:s"), $curDate->format("d-m-Y H:i:s"), $timezone, $query, $language, (array) $type);
              } else {
              $zLeadMessage = new ZLeadReader($lastAccess->format("d-m-Y H:i:s"), $curDate->format("d-m-Y H:i:s"), $timezone, $query, $language);
              }
              try {
              $zLeadMessage->read(function($item, $total) use (&$newLeads) {
              $newLeads = $total;
              }, $index, 0);
              } catch (Exception $err) {
              $newLeads = 0;
              }

              //Get news message of all types
              $user = User::getLogedInUser();
              $streamId = $this->model->streamId;
              $classificationData = array();
              for ($i = 1; $i <= 4; $i++) { //message types from 1 to 4 (favorite | achive | trash)
              //get Total
              $dlastAccess = $this->model->getStreamInfo($i);
              $dateStringLastAccess = $dlastAccess->format("Y-m-d H:i:s");
              $data = array();
              $data['total'] = 0;
              $data['new'] = 0;
              $result = Database::totalRowsWithWhere("messageactiondata", "userid IN (SELECT userid FROM users WHERE teamid = $user->teamId) AND streamid = $streamId AND type=$i");
              $data['total'] = $result->numRows;
              //get News
              $result = Database::totalRowsWithWhere("messageactiondata", "userid IN (SELECT userid FROM users WHERE teamid = $user->teamId) AND streamid = $streamId AND type=$i AND datecreated >= '$dateStringLastAccess' AND datecreated <= NOW()");
              $data['new'] = $result->numRows;

              $classificationData[$i] = $data;
              } */
            $data = new stdClass();
            $data->newLeads = $newLeads;
            $data->totalLeads = $totalLeads;
            $data->newMessages = $newMessages;
            $data->totalMessages = $totalMessages;
            $data->newSpamLeads = $newSpamLeads;
            $data->totalSpamLeads = $totalSpamLeads;
            $data->newSpamMessages = $newSpamMessages;
            $data->totalSpamMessages = $totalSpamMessages;
            $data->classificationData = $classificationData;
            echo json_encode($data);
            return 'info';
        }
        if (strtoupper($params[0]) == 'LOADSTREAM' || strtoupper($params[0]) == 'NEWSTREAM' || strtoupper($params[0]) == 'LOADSENTIMENTSTREAM') {
            //Language: 2 = vi, 0 = all
            $user = User::getLogedInUser();
            try {
                if ($user->type == '10') {
                    if ($tag == array('0') && $sentiment == 0) {
                        if ($messageAction == '' || $messageAction == 'spam') {
                            $spamQuery = json_decode(SpamMessages::getKeywords($this->model->streamId));
                            $spamAuthors = $spamQuery->author;
                            $spamSources = $spamQuery->source;
                            $items = Stream::getPulse($this->model->streamId, $startDate, $endDate, $index, $length, $source, $type, $tag);
                            if (is_array($items)) {
                                if ($messageAction !== 'spam') {
                                    foreach ($items as $key => $item) {
                                        if (is_array($spamAuthors))
                                            if (in_array($item->getLeadAuthor(), $spamAuthors)) {
                                                unset($items[$key]);
                                                continue;
                                            }
                                        if (is_array($spamSources))
                                            if (in_array($item->getSource(), $spamSources)) {
                                                unset($items[$key]);
                                                continue;
                                            }
                                    }
                                } else {
                                    foreach ($items as $key => $item) {
                                        if (is_array($spamSources) || is_array($spamAuthors)) {
                                            if (!in_array($item->getLeadAuthor(), $spamAuthors) && !in_array($item->getSource(), $spamSources)) {
                                                unset($items[$key]);
                                                continue;
                                            }
                                        } else {
                                            unset($items[$key]);
                                        }
                                    }
                                }
                                while (count($items) == 0 && is_array($items)) {
                                    $index += $length;
                                    $items = Stream::getPulse($this->model->streamId, $startDate, $endDate, $index, $length, $source, $type, $tag);
                                    if ($messageAction !== 'spam') {
                                        if (is_array($items))
                                            foreach ($items as $key => $item) {
                                                if (is_array($spamAuthors))
                                                    unset($items[$key]);
                                                if (in_array($item->getLeadAuthor(), $spamAuthors)) {
                                                    unset($items[$key]);
                                                    continue;
                                                }
                                                if (is_array($spamSources))
                                                    if (in_array($item->getSource(), $spamSources)) {
                                                        unset($items[$key]);
                                                        continue;
                                                    }
                                            }
                                    } else {
                                        if (is_array($items))
                                            foreach ($items as $key => $item) {
                                                if (is_array($spamSources) || is_array($spamAuthors)) {
                                                    if (!in_array($item->getLeadAuthor(), $spamAuthors) && !in_array($item->getSource(), $spamSources)) {
                                                        unset($items[$key]);
                                                        continue;
                                                    }
                                                } else {
                                                    unset($items[$key]);
                                                }
                                            }
                                    }
                                }
                            }
                        } else {
                            $messageType = 1;
                            $streamId = $this->model->streamId;
                            switch ($messageAction) {
                                case 'archive':
                                    $messageType = 2;
                                    break;
                                case 'spam':
                                    $messageType = 3;
                                    break;
                                case 'trash':
                                    $messageType = 4;
                                    break;
                            }

                            $this->model->updateAccess($messageType);

                            $messageIds = MessageAction::getMessageIds($streamId, $messageType, $index, $length);
                            $messages = Message::withId($messageIds);
                            if (count($messages) == 1)
                                $items[] = $messages;
                            else
                                $items = $messages;
                        }
                    }
                    else {
                        $items = Stream::getMessages($this->model->streamId, $startDate, $endDate, $tag, $sentiment, $source, $type, $index, $length);
                    }
                } else {
                    if ($tag == array('0') && $sentiment == 0) {
                        if ($messageAction == '' || $messageAction == 'spam') { //Get all without filter
                            if ($messageAction == '') {
                                $spamQuery = SpamMessages::getQuery($this->model->streamId);
                            } else {
                                $spamQuery = SpamMessages::getSQuery($this->model->streamId);
                            }
                            if ($spamQuery || $messageAction == '') {
                                $sourceQuery = '';
                                if ($source != '0') {
                                    $sourceQuery = ' @source "' . urldecode($source) . '" ';
                                }
                                $zMessage = new ZPulseReader($startDate, $endDate, $timezone, $query . $spamQuery . $sourceQuery, $language);
                                if ($type != array('0')) {
                                    $zMessage = new ZPulseReader($startDate, $endDate, $timezone, $query . $spamQuery . $sourceQuery, $language, (array) $type);
                                }
                                //$reader = new ZPulseReader('25-03-2013', '28-03-2014', 7, '@thread "trend lite" | @content "trend lite" | (@lead "trend lite" @url facebook) | (@lead "trend lite" @content (samsung | ss | trend)) - ("thanh ly" | "thanh lý" | "can mua" | "cần mua" | "cần bán" | "can ban" | "op lung" | "ốp lưng" | "bao da")', array(2), array(4));
                                $items = array();
                                $threadId = '';
                                $signals = array();
                                $stream = $this->model;
                                $view = $this->view;
                                $leadData = array();
                                $totalReplies = 0;
                                try {
                                    $zMessage->read(function($item, $nreplies, $total) use (&$items, &$threadId, &$signals, $stream, &$reply, &$leadData, &$view, &$totalReplies) {
                                        //var_dump($nreplies);
                                        //First thread detected
                                        if ($threadId == '') {
                                            $threadId = $item->getThreadId();
                                            $leadData = array();
                                            $leadData["replies"] = array();
                                            $leadData["message"] = $item;
                                            $totalReplies = $nreplies;
                                            $leadData["type"] = $item->getType();
                                        }
                                        if ($threadId != $item->getThreadId()) {
                                            //var_dump($leadData);
                                            $message = $leadData["message"];
                                            $signal = Signal::withItem($message, $stream);
                                            $signal->leadData = $leadData;
                                            $signal->type = $message->getType();
                                            //var_dump($replies);
                                            $signal->totalReplies = $totalReplies;
                                            $signal->isRead = $message->isRead;
                                            //$signalController->save
                                            $signals[] = $signal;
                                            $view->model = $stream;
                                            $view->signals = $signals;
                                            $masterView = MasterView::getInstance();
                                            $masterView->streamView = $view;
                                            include("View/Mobile/Post/SinglePost.php");
                                            $masterView->error = '';
                                            $signals = array();
                                            ob_flush();
                                            flush();
                                            $leadData = array();
                                            $leadData["replies"] = array();
                                            $leadData["message"] = $item;
                                            $leadData["type"] = $item->getType();
                                            $threadId = $item->getThreadId();
                                        }
                                        
                                        //Load total replies
                                        $messageId = $item->getId();
                                        $item->isRead = bpServer::isRead($stream->streamId, $threadId, $messageId);
                                        if ($messageAction == null)
                                            $messageAction = '';
                                        if ($messageAction == '' || $messageAction == 'spam') { //Already have replies
                                            $text = $item->getText();
                                            $lead = $item->getLead();
                                            $replyDate = DateTime::createFromFormat("Y-m-d H:i:s", $item->getTime());
                                            $text = str_replace("\n", "<br>", $text);
                                            $reply = array();
                                            $reply['text'] = Signal::removeLink($text);
                                            $reply['time'] = $replyDate;
                                            $reply['author'] = $item->getAuthor();
                                            $reply['authorUrl'] = $item->getAuthorUrl();
                                            $reply['messageId'] = $item->getId();
                                            $reply['threadId'] = $item->getThreadId();
                                            $reply['numberOfLikes'] = $item->getNumberOfLikes();
                                            if ($item->getSource() == 'plus.google.com') {
                                                $urlParams = explode('/', $item->getURL());
                                                $reply['guserid'] = $urlParams[3];
                                            }

                                            if ($item->getSource() == 'www.facebook.com') {
                                                $postParams = explode('/', $item->getURL());
                                                $postData = $postParams[5];
                                                $data = explode('?comment_id=', $postData);
                                                $reply['fbUserId'] = $postParams[3];
                                                $reply['fbPostId'] = $data[0];
                                                if (count($data) > 1)
                                                    $reply['fbCommentId'] = $data[1];
                                                else
                                                    $reply['fbCommentId'] = '';
                                            }

                                            if (strlen($item->getText()) != strlen($item->getLead()))
                                                $leadData["replies"][] = $reply;
                                        }
                                    }, $index, $length);
                                    
                                } catch (Exception $err) {
                                    echo $err->getMessage();
                                    exit();
                                }
                                $this->model->updateAccess();
                            }
                            exit();
                        } else { //Get with specified messageid
                            $messageType = 1;
                            $streamId = $this->model->streamId;
                            switch ($messageAction) {
                                case 'archive':
                                    $messageType = 2;
                                    break;
                                case 'spam':
                                    $messageType = 3;
                                    break;
                                case 'trash':
                                    $messageType = 4;
                                    break;
                            }

                            $this->model->updateAccess($messageType);

                            $messageIds = MessageAction::getMessageIds($streamId, $messageType, $index, $length);

                            $zMessage = new ZPostReader($messageIds['messageId'], 7);
                            $zMessage->read(function($item, $total) use (&$items) {
                                $items[] = $item;
                            });
                        }
                    } else {
                        $items = Stream::getMessages($this->model->streamId, $startDate, $endDate, $tag, $sentiment, $source, $type, $index, $length);
                    }
                }
                $signals = array();
                $tempdata = array();
                $threadId = 0;
                if (is_array($items)) {
                    foreach ($items as $message) { //process replies
                        $threadId = $message->getThreadId();
                        //Load total replies
                        $date = new DateTime($startDate);
                        $messageId = $message->getId();
                        $message->isRead = bpServer::isRead($this->model->streamId, $threadId, $messageId);
                        if ($tag != 0 || $sentiment != 0) {
                            $text = $message->getText();
                            $lead = $message->getLead();
                            $replyDate = DateTime::createFromFormat("Y-m-d H:i:s", $message->getTime());
                            $text = str_replace("\n", "<br>", $text);

                            $reply['text'] = Signal::removeLink($text);
                            $reply['time'] = $replyDate;
                            $reply['author'] = $message->getAuthor();
                            $reply['authorUrl'] = $message->getAuthorUrl();
                            $reply['messageId'] = $message->getId();
                            $reply['threadId'] = $message->getThreadId();
                            $reply['numberOfLikes'] = $message->getNumberOfLikes();
                            if ($message->getSource() == 'plus.google.com') {
                                $urlParams = explode('/', $message->getURL());
                                $reply['guserid'] = $urlParams[3];
                            }

                            if ($message->getSource() == 'www.facebook.com') {
                                $postParams = explode('/', $message->getURL());
                                $postData = $postParams[5];
                                $data = explode('?comment_id=', $postData);
                                $reply['fbUserId'] = $postParams[3];
                                $reply['fbPostId'] = $data[0];
                                if (count($data) > 1)
                                    $reply['fbCommentId'] = $data[1];
                                else
                                    $reply['fbCommentId'] = '';
                                //$reply['fbObjectId'] = Facebook::getFacebookObjectId($reply['fbUserId'], $reply['fbPostId']);
                            }
                            //$tempdata[$threadId]["replies"] = array();
                            if (strlen($message->getText()) != strlen($message->getLead()))
                                $tempdata[$threadId]["replies"][] = $reply;
                            $tempdata[$threadId]["message"] = $message;
                            $tempdata[$threadId]["type"] = $message->getType();
                        } else {
                            if ($messageAction == null)
                                $messageAction = '';
                            if ($messageAction == '' || $messageAction == 'spam') { //Already have replies
                                $text = $message->getText();
                                $lead = $message->getLead();
                                $replyDate = DateTime::createFromFormat("Y-m-d H:i:s", $message->getTime());
                                $text = str_replace("\n", "<br>", $text);

                                $reply['text'] = Signal::removeLink($text);
                                $reply['time'] = $replyDate;
                                $reply['author'] = $message->getAuthor();
                                $reply['authorUrl'] = $message->getAuthorUrl();
                                $reply['messageId'] = $message->getId();
                                $reply['threadId'] = $message->getThreadId();
                                $reply['numberOfLikes'] = $message->getNumberOfLikes();
                                if ($message->getSource() == 'plus.google.com') {
                                    $urlParams = explode('/', $message->getURL());
                                    $reply['guserid'] = $urlParams[3];
                                }

                                if ($message->getSource() == 'www.facebook.com') {
                                    $postParams = explode('/', $message->getURL());
                                    $postData = $postParams[5];
                                    $data = explode('?comment_id=', $postData);
                                    $reply['fbUserId'] = $postParams[3];
                                    $reply['fbPostId'] = $data[0];
                                    if (count($data) > 1)
                                        $reply['fbCommentId'] = $data[1];
                                    else
                                        $reply['fbCommentId'] = '';
                                    //$reply['fbObjectId'] = Facebook::getFacebookObjectId($reply['fbUserId'], $reply['fbPostId']);
                                }
                                //$tempdata[$threadId]["replies"] = array();
                                if (strlen($message->getText()) != strlen($message->getLead()))
                                    $tempdata[$threadId]["replies"][] = $reply;
                                $tempdata[$threadId]["message"] = $message;
                                $tempdata[$threadId]["type"] = $message->getType();
                            }
                            else {
                                //Get new replies
                                $reader = new ZMessageReader($startDate, $endDate, $timezone, $query, $language);
                                $reader->filterByThread($threadId);
                                try {
                                    $_SESSION['item'] = array();
                                    $reader->read(function($item, $total) {
                                        $_SESSION['item'][] = $item;
                                    }, 0, 10);
                                    foreach ($_SESSION['item'] as $item) {
                                        $text = $item->getText();
                                        $lead = $item->getLead();
                                        $replyDate = DateTime::createFromFormat("Y-m-d H:i:s", $item->getTime());
                                        $text = str_replace("\n", "<br>", $text);

                                        $reply['text'] = Signal::removeLink($text);
                                        $reply['time'] = $replyDate;
                                        $reply['author'] = $item->getAuthor();
                                        $reply['messageId'] = $item->getId();
                                        $reply['threadId'] = $item->getThreadId();
                                        $reply['numberOfLikes'] = $item->getNumberOfLikes();
                                        if ($item->getSource() == 'plus.google.com') {
                                            $urlParams = explode('/', $item->getURL());
                                            $reply['guserid'] = $urlParams[3];
                                        }

                                        if (strlen($item->getText()) != strlen($item->getLead()))
                                            $tempdata[$threadId]["replies"][] = $reply;
                                        $tempdata[$threadId]["message"] = $item;
                                        $tempdata[$threadId]["type"] = $message->getType();
                                    }
                                } catch (Exception $e) {
                                    
                                }
                            }
                        }
                    }
                }
                foreach ($tempdata as $key => $value) {
                    $signal = Signal::withItem($value["message"], $this->model);
                    $signal->leadData = $value;
                    $signal->type = $value["type"];
                    $message = $value["message"];
                    $signal->totalReplies = $message->totalReplies;
                    if (!$signal->totalReplies) {
                        $signal->totalReplies = count($value['replies']);
                    }
                    $signal->isRead = $message->isRead;
                    //$signalController->save
                    $signals[] = $signal;
                }
            } catch (Exception $err) {
                $error = $err->getMessage();
            }
            //echo $error;
        }

        //Get for spams
        $this->view->model = $this->model;
        $this->view->signals = $signals;
        $masterView = MasterView::getInstance();
        $masterView->streamView = $this->view;
        $masterView->error = $error;
    }

    public function renderSignals($startDate, $endDate, $language = 0, $tag = 0, $sentiment = 0) {
        //Need to edit
        $query = trim($this->model->query);
        $timezone = 7;
        //Param parser
        #remove the directory path we don't want 
        $url = $_SERVER['REQUEST_URI'];
        $request = ltrim($url, '/');
        if (strpos($request, '?') != '') {
            $request = substr($request, 0, strpos($request, "?"));
        }
        #split the path by '/'
        $params = split("/", $request);
        $error = '';
        $spikes = array();
        if (strtoupper($params[2]) != 'VIEWPORT') {
            //Language: 2 = vi, 0 = all
            try {
                $filter['streamId'] = base64_encode($this->model->streamId);
                $filter['dateFrom'] = $startDate;
                $filter['dateTo'] = $endDate;
                $spikes = SignalsHelper::getSpike($filter);
            } catch (Exception $err) {
                echo $err->getMessage();
            }
        }
        $this->view->model = $this->model;
        $this->view->spikes = $spikes;
        $masterView = MasterView::getInstance();
        $masterView->streamView = $this->view;
        $masterView->error = $error;
    }

    public function renderEmail($date, $index, $length) {
        //Need to edit                
        $query = trim($this->model->query);
        $timezone = 7;

        //Language: 2 = vi, 0 = all
        $zMessage = new ZMessageReader($date, $date, $timezone, $query, $language, $index, $length);
        $collection = $zMessage->read();
        $signals = array();
        $items = $collection->getItems();
        for ($i = 0; $i < 10; $i++) {
            $signal = Signal::withItem($items[$i], $this->model);
            $signalController = new SignalController($signal, new SignalView());
            //$signalController->save();
            $signals[] = $signal;
        }

        $this->view->model = $this->model;
        $this->view->signals = $signals;
        $masterView = MasterView::getInstance();
        $masterView->streamView = $this->view;
    }

    public static function getStream($folderId) {
        $userId = User::getCurrentUserId();
        $user = User::withId($userId);
        $managerId = $user->managerId;
        $teamId = $user->teamId;
        //$query = "SELECT * FROM streams LEFT JOIN users ON streams.userid = users.userid WHERE streams.folderid = $folderId AND (users.userid IN (SELECT userid FROM users WHERE teamid='$teamId'))";
        $query = "SELECT * FROM streams LEFT JOIN users ON streams.userid = users.userid WHERE streams.folderid = $folderId";
        $result = Database::getInstance()->query($query);
        if ($result->returnCode == 200) {  //OK
            if ($result->dataTable->numOfRow > 0) {
                $rows = $result->dataTable->rows;
                $streams = array();
                foreach ($rows as $row) {
                    $stream = new Stream();
                    $stream->streamId = $row["streamid"];
                    $stream->userId = $row["userid"];
                    $stream->name = $row["name"];
                    $stream->type = $row["type"];
                    $stream->query = $row["query"];
                    $stream->language = $row["language"];
                    $stream->location = $row["location"];
                    $stream->platform = $row["platform"];
                    $stream->externalSources = $row["externalsources"];
                    $stream->folderId = $row["folderid"];
                    $streams[] = $stream;
                }
                return $streams;
            } else
                return array();
        }
    }

    /**
     * Update folder infos or add new stream to folder
     */
    public function save() {
        $model = $this->model;
        $model->name = addslashes($model->name);
        $model->query = addslashes($model->query);
        if ($model->streamId !== null) {
            $query = "SELECT * FROM streams WHERE streamid = '$model->streamId'";
            $result = Database::getInstance()->query($query);
            if ($result->returnCode == 200) {  //OK
                if ($result->dataTable->numOfRow > 0) {
                    $query = "UPDATE streams
                        SET userid='$model->userId', 
                        name='$model->name', 
                        type='$model->type', 
                        query='$model->query',
                        language='$model->language',
                        location='$model->location',
                        platform='$model->platform',
                        externalsources='$model->externalSources',
                        folderid='$model->folderId' 
                        WHERE streamid = $model->streamId";
                    Database::getInstance()->query($query);
                    return Stream::withId(base64_encode($model->streamId));
                }
            }
        } else {
            $model->streamId = Database::getID("streams", "streamid");
            Database::getInstance()->query("INSERT INTO streams
                        (streamid, userid, name, type, query, language, location,
                         platform, externalsources, folderid, datecreated) VALUES
                        ('$model->streamId', '$model->userId', '$model->name', 
                        '$model->type', '$model->query', 
                        '$model->language', '$model->location', 
                        '$model->platform', '$model->externalSources',
                        '$model->folderId', CURDATE())");
            return Stream::withId(base64_encode($model->streamId));
        }
    }

    /**
     * Delete this stream
     */
    public function delete() {
        $model = $this->model;
        $query = "DELETE FROM streams WHERE streamid = $model->streamId";
        Database::getInstance()->query($query);
        return true;
    }

}

?>
